// Copyright 2019 The rhyme_lph Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// h [author] rhyme_lph
// y [email]  rhymelph@gmail.com
// f [github] https://github.com/rhymelph

import 'package:base_plugin/base_plugin.dart';
import 'package:finance_app/generated/a.dart';
import 'package:finance_app/generated/l10n.dart';
import 'package:finance_app/src/common/app_colors.dart';
import 'package:finance_app/src/common/config.dart';
import 'package:finance_app/src/entities/company_entity.dart';
import 'package:finance_app/src/entities/dashboard_entity.dart';
import 'package:finance_app/src/http_service/http_dashboard_service.dart';
import 'package:finance_app/src/mixin/chat_room_action_mixin.dart';
import 'package:finance_app/src/mixin/check_plan_mixin.dart';
import 'package:finance_app/src/mixin/scroll_to_hide_mixin.dart';
import 'package:finance_app/src/page/tutorial/helper/tutorial_mark.dart';
import 'package:finance_app/src/page/tutorial/tutorial_page.dart';
import 'package:finance_app/src/provider/dashboard/dashboard_contacts_provider.dart';
import 'package:finance_app/src/provider/dashboard/dashboard_overview_provider.dart';
import 'package:finance_app/src/router_gen/router_gen_providers.dart';
import 'package:finance_app/src/utils/permission_utils.dart';
import 'package:finance_app/src/widgets/bottom_sheet/dashboard_add_bottom_sheet.dart';
import 'package:finance_app/src/widgets/button/normal_float_svg_button.dart';
import 'package:finance_app/src/widgets/common_tab_bar.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:onesignal_flutter/onesignal_flutter.dart';

import '../dashboard_provider.dart';
import 'dashboard_transactions_provider.dart';

class DashboardViewProvider extends BaseProvider<DashboardEntity>
    with ScrollToHideMixin, ChatroomActionMixin, CheckPlanMixin {
  List<String> get tabList => ['overview', 'transactions', 'contacts'];

  ScrollController controller = ScrollController();
  List<CompanyEntity> companies;

  GlobalKey tabBarKey = GlobalKey();
  GlobalKey ocrCameraKey = GlobalKey();
  GlobalKey transactionKey = GlobalKey();

  @override
  Future get dataFuture => HttpDashboardService.dashboard();

  void onRefreshDashboard({bool refreshTransaction, bool refreshOverview}) {
    if (!Config.hasPermission(PermissionUtils.homeDashboard)) return;

    loadData();
    if (refreshOverview != null && refreshOverview) {
      getChildProvider<DashboardOverviewProvider>()
          ?.onRefreshDashboardOverview();
    }

    if (refreshTransaction != null && refreshTransaction) {
      getChildProvider<DashboardTransactionsProvider>()?.onLoadRefreshData();
    }
  }

  @override
  void initState() {
    super.initState();
  }

  void onNavCamera() async {
    if (isPlanExpired()) return;
    final result = await Routes.navigateTo(RouterGenProviders.ocrCameraPage);
    print(result);
  }

  void onNavAdd() {
    if (isPlanExpired()) return;
    obtainContext?.call((context) async {
      await showDashboardAddBottomSheet(context);
      onRefreshDashboard(refreshOverview: true, refreshTransaction: true);
    });
  }

  void onFilter() {}

  @override
  List<BaseProvider> registerChildProviders() {
    return [
      DashboardOverviewProvider(),
      DashboardTransactionsProvider(),
      DashboardContactsProvider(),
    ];
  }

  void onNavUnPaidBill() {
    if (!Config.hasPermission(PermissionUtils.bill)) {
      showToast(S.current.no_permissions_to_view);
      return;
    }
    Routes.navigateTo(RouterGenProviders.allTransactionsPage,
        params: {'type': 5, 'initFilter': 'Unpaid Bill'});
  }

  void onNavUnpaidInvoice() {
    if (!Config.hasPermission(PermissionUtils.invoice)) {
      showToast(S.current.no_permissions_to_view);
      return;
    }
    Routes.navigateTo(RouterGenProviders.allTransactionsPage, params: {
      'type': 2,
      'initFilter': 'Unpaid',
    });
  }

  void onNavCashBalance() async {
    if (!Config.hasPermission(PermissionUtils.cashBank)) {
      showToast(S.current.no_permissions_to_view);
      return;
    }
    await Routes.navigateTo(RouterGenProviders.cashAndBankPage);
    loadData();
  }

  void onNavSub() {
    Routes.navigateTo(RouterGenProviders.subscriptionPage);
  }

  @override
  FutureOr<DashboardEntity> transformData(
      DashboardEntity d, bool isCache) async {
    if (Config.userProfile.showTutorial == 1 &&
        Config.hasPermission(PermissionUtils.hrPayroll)) {
      // if (!kDebugMode)
      Future.delayed(Duration(milliseconds: 500))
          .then((value) => showTutorial());
    }
    return super.transformData(d, isCache);
  }

  Future<void> showTutorial() async {
    Config.userProfile.showTutorial = 0;
    List<TutorialMark> marks = [
      TutorialMark(
          key: tabBarKey,
          canTap: false,
          widget: Container(
            color: Colors.white,
            height: 50,
            child: AbsorbPointer(
              child: DefaultTabController(
                length: 3,
                child: CommonTabBar(
                  tabs: tabList
                      .map((e) => MyTab(
                            text: getTabTitle(e),
                          ))
                      .toList(),
                ),
              ),
            ),
          )),
      TutorialMark(
          key: ocrCameraKey,
          widget: NormalFloatSvgButton(
            disabledColor: aceBlueColor,
            asset: A.assetsImagesDashboardPhoto,
          )),
      TutorialMark(
        key: getParentProvider<DashboardProvider>().assistantKey,
        widget: SvgPicture.asset(
          A.assetsImagesStyleAce_Assistant_Icon,
        ),
      ),
      TutorialMark(
          key: getParentProvider<DashboardProvider>().drawerKey,
          widget: Icon(Icons.menu, color: Colors.white)),
      TutorialMark(
          key: transactionKey,
          widget: NormalFloatSvgButton(
            disabledColor: aceBlueColor,
            asset: A.assetsImagesDashboardAdd,
          )),
    ];

    obtainContext?.call((context) async {
      await Navigator.of(context).push(PageRouteBuilder(
          opaque: false,
          reverseTransitionDuration: Duration(milliseconds: 100),
          transitionDuration: Duration.zero,
          pageBuilder: (BuildContext context, _, __) => TutorialPage(
                marks: marks,
              )));
      onNavAdd();
    });
  }

  String getTabTitle(String key) {
    switch (key) {
      case 'overview':
        return S.current.overview;
        break;
      case 'transactions':
        return S.current.transactions;
        break;
      case 'contacts':
        return S.current.contacts;
        break;
      default:
        return '';
    }
  }
}
